package com.okhttp.retrofit.callfactory;

import com.okhttp.utils.RetrofitLog;
import okhttp3.Call;
import okhttp3.HttpUrl;
import okhttp3.Request;
import org.jetbrains.annotations.NotNull;

/**
 * @author YLG
 * @Datetime 2020/4/21-10:48 PM
 * @Version v1.0
 * @description 根据请求头来修改baseurl值
 * <pre>
 *   retrofitBuilder.callFactory(new ReplaceBaseUrlCallFactory(OkHttpClient){
 *
 *       @Override
 *       protected HttpUrl getNewUrl(String baseUrlName, Request request) {
 *         return null;
 *       }
 *     });
 * </pre>
 */
public abstract class ReplaceBaseUrlCallFactory implements Call.Factory {

  public static final String BASEURL_TAG="host";

  private Call.Factory mDelegate;

  public ReplaceBaseUrlCallFactory(Call.Factory delegate){
    this.mDelegate=delegate;
  }

  @NotNull
  @Override
  public Call newCall(@NotNull Request request) {
    String baseUrlName = request.header(BASEURL_TAG);
    if (baseUrlName != null) {
      okhttp3.HttpUrl newHttpUrl = getNewUrl(baseUrlName, request);
      if (newHttpUrl != null) {
        Request newRequest = request.newBuilder().url(newHttpUrl).build();
        return mDelegate.newCall(newRequest);
      } else {
        RetrofitLog.d("ReplaceBaseUrlCallFactory","new baseurl is null");
      }
    }
    return mDelegate.newCall(request);
  }

   protected abstract HttpUrl getNewUrl(String baseUrlName, Request request);
}
